#include "EventHandler.h"
#include "GLDrawer.h"
#include "MainWindow.h"

bool EventHandler::handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osg::Object *, osg::NodeVisitor *)
{
	MainWindow::MouseMode mouseMode = MainWindow::instance()->getMouseMode();
	switch (ea.getEventType())
	{
	case (osgGA::GUIEventAdapter::RESIZE):
		{
			_drawer->getCameraController()->resize((float)_drawer->width() / (float)_drawer->height());
			return true;
		}
	case (osgGA::GUIEventAdapter::SCROLL):
		{
			float dz = (ea.getScrollingMotion() == osgGA::GUIEventAdapter::SCROLL_UP) ? -1.0f : 1.0f;
			_drawer->getCameraController()->zoom(dz);
			return true;
		}
	case (osgGA::GUIEventAdapter::PUSH):
		{
			_savedX = ea.getX();
			_savedY = ea.getY();
			_savedButton = ea.getButton();
			return true;
		}
	case (osgGA::GUIEventAdapter::RELEASE):
		{

			return true;
		}
	case (osgGA::GUIEventAdapter::DRAG):
		{
			int dx = ea.getX() - _savedX;
			int dy = ea.getY() - _savedY;
			if (mouseMode == MainWindow::ZOOM && _savedButton == 1)
			{
				_drawer->getCameraController()->zoom((float)-dy * 0.2f);
			}
			else if (mouseMode == MainWindow::ROTATE && _savedButton == 1)
			{
				_drawer->getCameraController()->rotate(dx, dy);
			}
			else if ((mouseMode == MainWindow::TRANSLATE && _savedButton == 1) || ((_savedButton == 2 || _savedButton == 4) && mouseMode != MainWindow::SELECT))
			{
				_drawer->getCameraController()->move(dx, dy);
			}
			_savedX = ea.getX();
			_savedY = ea.getY();
			return true;
		}
	}
	return false;
}